package com.james.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.james.constant.RedisConstant;
import com.james.constant.SetmealDeleteFileByCheckgroupException;
import com.james.dao.SetmealDao;
import com.james.entity.PageResult;
import com.james.entity.QueryPageBean;
import com.james.pojo.Setmeal;
import com.james.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ACT
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("D:/JavaProduct/MedicalHealth/health_parent/health_mobile/src/main/webapp/pages")
//    @Value("${out_put_path}")
    private String outPutPath ;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //新增套餐信息
        setmealDao.add(setmeal);
        //获取自增id
        Integer id = setmeal.getId();
        //设置检查组和套餐的关联关系
        setSetmealAndCheckgroup(id, checkgroupIds);
        //将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());

        //新增套餐后需要重新生成静态页面
//        generateMobileStaticHtml();
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmeals = setmealDao.selectByCondition(queryString);
        return new PageResult(setmeals.getTotal(), setmeals.getResult());
    }

    @Override
    public List<Integer> findCheckGrouupIdsBySetmealIds(Integer id) {
        return setmealDao.findCheckGrouupIdsBySetmealIds(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //获取编辑前数据库保存的图片
        String img = setmealDao.findImgBySetmealId(setmeal.getId());
        //删除Redis中的图片
        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        //编辑套餐基本信息
        setmealDao.edit(setmeal);
        //将新图片名称保存到Redis
        savePic2Redis(setmeal.getImg());
        //删除套餐与检查组原有关联
        setmealDao.deleteAssociation(setmeal.getId());
        //编辑套餐的检查组信息
        setSetmealAndCheckgroup(setmeal.getId(), checkgroupIds);
    }

    @Override
    public void delete(Integer id) throws SetmealDeleteFileByCheckgroupException {
        Long count = setmealDao.findCheckGroupCountBySetmealId(id);
        if (count > 0) {
            throw new SetmealDeleteFileByCheckgroupException();
        }
        String img = setmealDao.findImgBySetmealId(id);
        setmealDao.delete(id);
        //删除Redis中的图片
        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    /**
     * 将图片名称保存到Redis
     * @param img 图片名称
     */
    private void savePic2Redis(String img) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
    }

    /**
     * 设置检查组与套餐关联关系
     * @param id 套餐id
     * @param checkgroupIds 检查组ids
     */
    private void setSetmealAndCheckgroup(Integer id, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", id);
                map.put("checkgroup_id", checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }

    /**
     * 生成静态页面
     */
    private void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = setmealDao.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面
        generateMobileSetmealDetailHtml(setmealList);
    }

    /**
     * 生成套餐列表静态页面
     * @param setmealList 套餐列表
     */
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    /**
     * 生成套餐详情静态页面
     * @param setmealList 套餐对象集合
     */
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal", this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    /**
     * 根据模板生成静态页面
     * @param templateName 模板名称
     * @param htmlPageName 静态页面名称
     * @param dataMap 所需数据集
     */
    private void generateHtml(String templateName,String htmlPageName,Map<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成静态文件
            out = new BufferedWriter(
                    new OutputStreamWriter(
                            new FileOutputStream(
                                    new File(outPutPath + "\\" + htmlPageName))));
            //输出文件
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}
